#include <stdio.h>
#include <stdlib.h>

struct list
{
  struct list* next,*prev;
  int data;
};

void init_list(struct list**);
void add_data(struct list*,int);
void display(struct list*);
void del_data(struct list*,int);
void del_list(struct list*);

int main(int argc, char *argv[])
{
  struct list* head;
  init_list(&head);
  add_data(head,1);
  add_data(head,2);
  add_data(head,3);
  add_data(head,4);
  display(head);
  del_data(head,2);
  display(head);
  del_list(head);
  free(head);
  head = NULL;
  display(head);
  return 0;
}

void init_list(struct list** head)
{
  *head = malloc(sizeof(struct list));
  (*head)->next = (*head)->prev = *head;
}

void add_data(struct list* head,int data)
{
  struct list* new_node;
  new_node = malloc(sizeof(struct list));
  new_node->data = data;
  new_node->next = head;
  new_node->prev = head->prev;
  
  head->prev->next = new_node;
  head->prev = new_node;
}

void display(struct list* head)
{
  if(head == NULL || head->next == head)
  {
    printf("empty\n");
    return;
  }
  struct list* tmp;
  tmp = head->next;
  while(tmp != head)
  {
    printf("%d ",tmp->data);
    tmp = tmp->next;
  }
  printf("\n");
}

void del_data(struct list* head,int data)
{
  if(head == NULL || head->next == head)
  {
    printf("empty\n");
    return;
  }

  struct list* tmp;
  tmp = head->next;
  while(tmp != head)
  {
    if(tmp->data == data)
    {
      break;
    }
    else
    {
      tmp = tmp->next;
    }
  }

  if(tmp == head)
  {
    printf("no find\n");
    return;
  }
  else
  {
    tmp->prev->next = tmp->next;
    tmp->next->prev = tmp->prev;
    free(tmp);
    tmp = NULL;;
    tmp = NULL;
  }
}

void del_list(struct list* head)
{
  if(head == NULL || head->next == head)
  {
    return;
  }
  struct list* tmp;
  struct list* prev;
  tmp = head->next;
  while(tmp != head)
  {
    prev = tmp;
    tmp = tmp->next;
    free(prev);
    prev = NULL;
  }
}
